<template>
    <div>
        <van-nav-bar title="商品列表" left-text="返回" left-arrow @click-left="onClickLeft" />

        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" offset="20">
                <van-card v-for="item in list" :key="item" :price="item.goods_price" :title="item.goods_name"
                    :thumb="item.goods_big_logo" @click="pushdetail(item.goods_id)" />
            </van-list>
        </van-pull-refresh>

    </div>
</template>

<script setup>
import { ref } from 'vue';
import { showToast } from 'vant';
//引入路由
import { useRouter, useRoute } from 'vue-router'
//实例化
const router = useRouter()
const route = useRoute()
import axios from '../request'
//返回上一级
const onClickLeft = () => router.go(-1)
//上拉加载,下拉刷新------------------------------------
const listinfo = ref({
    pagenum: 1,
    pagesize: 10,
})
//总数据
const total = ref(0)
const list = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);

const onLoad = () => {
    if (refreshing.value) {
        list.value = [];
        refreshing.value = false;
        listinfo.value.pagenum = 1;
        total.value = 0
    }
    //最大
    const maxpage = Math.ceil(total.value / listinfo.value.pagesize)
    if (maxpage == 0) {
        console.log('第一次进入')
    } else {
        if (listinfo.value.pagenum >= maxpage) {
            showToast('没有更多数据了');
            finished.value = true;
            return
        } else {
            listinfo.value.pagenum += 1
        }
    }
    axios.get('https://api-hmugo-web.itheima.net/api/public/v1/goods/search', {
        params: {
            cid: route.query.cid,
            ...listinfo
        },
    }).then((res) => {
        list.value = list.value.concat(res.goods)
        total.value = res.total
        loading.value = false;
    })
};

const onRefresh = () => {
    // 清空列表数据
    finished.value = false;

    // 重新加载数据
    // 将 loading 设置为 true，表示处于加载状态
    loading.value = true;
    onLoad();
};
//点击二级分类子项，跳转至详情页
const pushdetail = (id) => {
    router.push({
        path: '/detail',
        query: {
            id
        }
    })
}
</script>

<style lang="scss" scoped></style>